<template>
  <div id="addonline">
    <el-breadcrumb separator="/">
      <el-breadcrumb-item>首页</el-breadcrumb-item>
      <el-breadcrumb-item>新增团购券</el-breadcrumb-item>
    </el-breadcrumb>
    <div class="home-page"
      ref="wrap">
      <el-form :model="form"
        :rules="rules"
        ref="form"
        :disabled="type"
        :label-width="formLabelWidth">
        <h3 class="title">团购券基本信息</h3>
        <div style="margin-left:50px">
          <el-button type="primary"
            size="small"
            @click="add">添加优惠券</el-button>
          <!-- 优惠券 -->
          <el-table :data="selectedCouponList"
            style="width: 100%;margin:30px 0"
            max-height="500">
            <el-table-column prop="id"
              label="ID"
              width="120">
            </el-table-column>
            <el-table-column prop="typeName"
              label="券类型"
              width="120">
            </el-table-column>
            <el-table-column prop="name"
              label="券名称"
              width="120">
            </el-table-column>
            <el-table-column prop="num"
              label="券张数"
              width="120">
            </el-table-column>
            <el-table-column prop="faceValueName"
              label="券说明">
            </el-table-column>
            <el-table-column prop="doorsillMoneyName"
              label="使用门槛">
            </el-table-column>
            <el-table-column prop="stateName"
              label="状态">
            </el-table-column>
            <el-table-column label="有效期"
              prop="indate"
              width="260px">
            </el-table-column>
            <el-table-column fixed="right"
              label="操作">
              <template slot-scope="scope">
                <el-button @click="deletes(scope.$index,scope.row)"
                  type="text"
                  size="small">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <el-form-item label="售卖价格"
          prop="money">
          <el-input-number v-model="form.money"
            style="width:365px;"
            controls-position="right"
            :min="1"
            size="small"
            :max="10000"></el-input-number>
        </el-form-item>
        <el-form-item label="出售数量"
          prop="sellNum">
          <el-input-number v-model="form.sellNum"
            style="width:365px;"
            controls-position="right"
            :min="1"
            size="small"
            :max="10000"></el-input-number>
        </el-form-item>
        <el-form-item label="购买限制"
          prop="quota"
          class="quota">
          每人限购
          <el-input-number v-model="form.quota"
            style="width:161px;margin:0 10px;"
            controls-position="right"
            :min="1"
            :max="10000"></el-input-number>
          次（限购次数最小为1）
        </el-form-item>
        <el-form-item label="销售日期"
          required>
          <el-radio-group v-model="form.activity">
            <div class="times"
              style="height:34px;line-height:34px">
              <el-radio :label="1"
                style="float:left;">
                长期
              </el-radio><br>
              <el-radio :label="2">
                时间周期
              </el-radio>
              <el-form-item prop="startEndTime"
                style="margin-left:10px"
                v-if="form.activity ==2">
                <el-date-picker v-model="form.startEndTime"
                  type="daterange"
                  size="small"
                  value-format="yyyy-MM-dd"
                  :picker-options="pickerOptions0"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  style="width:285px;height:34px;">
                </el-date-picker>
              </el-form-item>
            </div>
          </el-radio-group>
        </el-form-item>
        <h3 class="title">购券海报设置</h3>
        <el-form-item label="海报标题"
          :label-width="formLabelWidth"
          prop="name">
          <el-input v-model="form.name"
            type="textarea"
            style="width:365px;"
            maxlength="100"
            rows="4"></el-input>
        </el-form-item>
        <el-form-item label="海报封面"
          prop="poster">
          <el-upload class="avatar-uploader"
            action="https://jsonplaceholder.typicode.com/posts/"
            :show-file-list="false"
            :http-request="sendChange">
            <img v-if="form.poster"
              :src="form.poster"
              class="avatar"
              width="88"
              height="88" />
            <i v-else
              class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
          <p class="img-info">仅支持JPG, JPEG, BMP, PNG格式, 文件小于10M<br />(建议使用缕空白色图像, 最佳尺寸126 * 45px)</p>
        </el-form-item>
        <el-form-item label="联系电话"
          prop="phone">
          <el-input placeholder="请输入联系电话"
            style="width:365px;"
            v-model="form.phone"></el-input>
        </el-form-item>
        <el-form-item label="图文"
          prop="imageText">
          <QuillEdit v-model="form.imageText"
            :height="750" />
        </el-form-item>
      </el-form>
    </div>
    <!-- 选择优惠券 -->
    <el-dialog :title="title"
      :visible.sync="outerVisible"
      width="70%">
      <el-input style="width:200px;margin-bottom:15px;margin-right:15px"
        v-model="search"
        clearable
        placeholder="请输入券名称"></el-input>
      <el-button type="primary"
        @click="_reset"
        size="small"
        style="width:60px">
        <i class="el-icon-search"></i>
      </el-button>
      <div style="height:500px;overflow-y:auto;overflow-x:hidden">
        <table class="custom-1">
          <tr class="style">
            <th style="width:20px">
              <el-checkbox v-model="isAllChecked"
                @change="checkAllChange"></el-checkbox>
            </th>
            <th style="width:60px">ID</th>
            <th>
              券类型
            </th>
            <th>券名称</th>
            <th>券说明</th>
            <th>使用门槛</th>
            <th style="width:200px">有效期</th>
            <th>张数</th>
          </tr>
          <tr v-for="(item,index) in tableData"
            v-show="search_ == '' || item.name.indexOf(search_)>-1"
            :key="index">
            <td style="width:20px">
              <el-checkbox v-model="item.check"
                @click="checkChange(item)"></el-checkbox>
            </td>
            <td @click="checkChange(item)">{{item.id}}</td>
            <td @click="checkChange(item)">
              {{item.typeName}}
            </td>
            <td @click="checkChange(item)">
              {{item.name}}
            </td>
            <td @click="checkChange(item)">
              {{item.faceValueName}}
            </td>
            <td @click="checkChange(item)">
              {{item.doorsillMoneyName}}
            </td>
            <td @click="checkChange(item)">
              {{item.indate}}
            </td>
            <td>
              <el-input-number v-model="item.num"
                style="width:120px;margin:0 10px;"
                controls-position="right"
                :min="1"
                size="small"
                :disabled="!item.check"
                :max="100000">
              </el-input-number>
              <span>张</span>
            </td>
          </tr>
        </table>
      </div>

      <div slot="footer"
        class="dialog-footer">
        <el-button @click="outerVisible = false">取 消</el-button>
        <el-button type="primary"
          @click="SeeSure">确 定</el-button>
      </div>
    </el-dialog>
    <div class="information-btns"
      :style="{width:width}">
      <el-button type="primary"
        size="small" v-show="!type"
        @click="Sure('form')">
        保存
      </el-button>
      <el-button @click="back"
        size="small" v-show="!type">取消</el-button>
      <el-button @click="back"
        size="small" v-show="type">返回</el-button>
    </div>
  </div>
</template>
<script>
import {
  PullOnlinePurchase,
  RedactOnlinePurchase,
  PullCouponPackage,
  ActivityOnlinePurchase
} from "@/public/js/saleRoom";
// 富文本编辑器测试页面
import { upimg } from "@/public/js/setting";
const QuillEdit = () => import("@/public/component/QuillEdit");
export default {
  components: {
    QuillEdit
  },
  data() {
    var checkTime = (rule, value, callback) => {
      console.log("value", value);
      if (!value.length) {
        return callback(new Error("时间周期不能为空"));
      }
      if (new Date(value[1]).getTime() <= new Date(value[0]).getTime()) {
        callback(new Error("结束日期必须大于开始日期"));
      } else {
        callback();
      }
    };
    return {
      money: "",
      money2: "",
      title: "",
      couponIds_bag: [], //选择券包打钩的集合
      couponIds: [], //选择优惠券打钩的集合
      couponIds_id: [],
      tableData_bag2: [], //选择券包的数据渲染
      couponIds_bag_id: [],
      tableData2: [], //选择券包的数据渲染
      formLabelWidth: "120px",
      SeeData: {},
      tableData_bag: "", //券包
      outerVisible_bag: false,
      typeStr_bag: "全部类型",
      search_bag: "",
      oldPath: "",
      width: "",
      tableData: [], //优惠券
      selectedCouponList: [], // 已选中优惠券列表
      outerVisible: false,
      typeStr: "全部类型",
      search: "",
      search_: "",
      tickets: "",
      isAllChecked: false,
      state: "",
      id: "",
      type: false,
      form: {
        tickets: [],
        money: undefined,
        sellNum: 1,
        quota: 1,
        activity: 1,
        startEndTime: [],
        name: "",
        poster: "",
        phone: "",
        imageText: ""
      },
      content: "",
      rules: {
        money: [{ required: true, message: "请输入售卖价格", trigger: "blur" }],
        name: [{ required: true, message: "请输入海报标题", trigger: "blur" }],
        array_length: [
          { required: true, message: "请选择优惠券类型", trigger: "change" }
        ],
        sellNum: [
          { required: true, message: "请输入出售数量", trigger: "blur" }
        ],
        quota: [{ required: true, message: "请输入限购", trigger: "blur" }],
        poster: [
          { required: true, message: "请选择海报标题", trigger: "blur change" }
        ],
        phone: [{ required: true, message: "请输入联系电话", trigger: "blur" }],
        imageText: [
          { required: true, message: "请输入图文内容", trigger: "blur" }
        ],
        startEndTime: { validator: checkTime, trigger: "blur" }
      },
      pickerOptions0: {
        disabledDate(time) {
          return time.getTime() < Date.now() - 8.64e7; //如果没有后面的-8.64e7就是不可以选择今天的
        }
      }
    };
  },
  created() {
    this._PullOnlinePurchase();
    this.id = this.$route.query.id;
    this.state = this.$route.query.state;
    this.type = this.$route.query.type == 1;
    if (this.id) {
      this._ActivityOnlinePurchase();
    } else {
      this.form = {
        tickets: [],
        money: undefined,
        sellNum: 1,
        quota: 1,
        activity: 1,
        startEndTime: [],
        name: "",
        poster: "",
        phone: "",
        imageText: ""
      };
    }
  },
  mounted() {
    this.width = this.$refs.wrap.offsetWidth + "px";
  },
  methods: {
    //编辑获取活动详情数据
    _ActivityOnlinePurchase() {
      ActivityOnlinePurchase({ id: this.id }).then(res => {
        let buyInfo = res.data.buyInfo;
        this.selectedCouponList = buyInfo.coupons;
        this.form = {
          tickets: [],
          money: buyInfo.money,
          sellNum: buyInfo.sellNum,
          quota: buyInfo.quota,
          activity: buyInfo.activity,
          startEndTime: buyInfo.startTime
            ? [buyInfo.startTime, buyInfo.endTime]
            : [],
          name: buyInfo.name,
          poster: buyInfo.poster,
          phone: buyInfo.phone,
          imageText: buyInfo.imageText
        };
      });
    },
    //全选优惠券
    checkAllChange(val) {
      console.log(111);
      this.tableData.forEach(item => (item.check = val));
      console.log(this.tableData);
    },
    //单选
    checkChange(item) {
      item.check = !item.check;
      let flag = true;
      this.tableData.forEach(item => {
        if (!item.check) {
          flag = false;
        }
      });
      this.isAllChecked = flag;
    },
    sendChange(e) {
      var reader = new FileReader();
      reader.readAsDataURL(e.file);
      reader.onload = e => {
        let photoPath = e.target.result;
        upimg({
          nowPath: photoPath,
          oldPath: this.form.poster
        }).then(res => {
          this.form.poster = res.data.path;
        });
      };
    },
    // 获取在线购券下拉数据
    _PullOnlinePurchase() {
      var data = {
        search: "",
        free: 2
      };
      PullOnlinePurchase(data).then(res => {
        let tableData = res.data.couponList;
        tableData.forEach(item => (item.check = false));
        this.tableData = tableData;
        if (!this.id) {
          this.form.phone = res.data.landline;
        }
      });
    },
    //优惠券和券包切换
    add() {
      this.title = "新增优惠券";
      this.outerVisible = true;
      this.tableData.forEach(item => {
        item.check = false;
      });
      this.selectedCouponList.forEach(item => {
        this.tableData.forEach(_item => {
          if (item.id == _item.id) {
            _item.check = true;
            _item.num = item.num;
          }
        });
      });
    },
    //保存
    Sure(formNames) {
      if (!this.selectedCouponList.length) {
        this.$message.error("请选择优惠券");
        return false;
      }

      this.$refs[formNames].validate(valid => {
        if (valid) {
          if (this.form.quota > this.form.sellNum) {
            this.$message.error("限购次数不能大于出售数量");
            return false;
          }
          //组装数据

          let tickets = [];
          let {
            money,
            sellNum,
            quota,
            activity,
            startEndTime,
            name,
            poster,
            phone,
            imageText
          } = this.form;
          this.selectedCouponList.forEach(item => {
            tickets.push({
              ticketId: item.id,
              num: item.num
            });
          });
          let data = {
            id: this.id,
            money,
            sellNum,
            quota,
            tickets,
            activity,
            activityStart: startEndTime[0],
            activityEnd: startEndTime[1],
            name,
            poster,
            phone,
            imageText
          };
          console.log("data", data);

          RedactOnlinePurchase(data).then(res => {
            if (res.data.errCode == 0) {
              this.$message({
                message: this.id ? "修改成功" : "添加成功",
                type: "success"
              });
              this.$router.push("/index/OnlinePurchase");
            }
          });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },

    //优券包关闭按钮
    close_bag() {
      this.$refs.multipleTable_bag.clearSelection();
    },
    //优惠券弹出框确定按钮
    SeeSure() {
      this.selectedCouponList = this.tableData.filter(item => item.check);
      this.outerVisible = false;
    },
    returns() {
      this.$router.push("/index/OnlinePurchase");
    },
    //优惠券勾选
    handleSelectionChange(val) {
      val.forEach(item => {
        this.couponIds_id.push(item.id);
      });
      this.couponIds = val;
    },
    //删除优惠券
    deletes(index, row) {
      this.selectedCouponList.splice(index, 1);
    },
    handleSizeChange(value) {
      console.log(value);
      this.pageSize = value;
      this._PullOnlinePurchase();
    },
    handleCurrentChange(value) {
      console.log(value);
      this.pageNum = value;
      this._PullOnlinePurchase();
    },
    _reset() {
      this.search_ = this.search;
    },
    toggleSelection(rows) {
      if (rows) {
        rows.forEach(row => {
          this.$refs.multipleTable.toggleRowSelection(row);
        });
      } else {
        this.$refs.multipleTable.clearSelection();
      }
    },
    toggleSelection_bag(rows) {
      if (rows) {
        rows.forEach(row => {
          this.$refs.multipleTable_bag.toggleRowSelection(row);
        });
      } else {
        this.$refs.multipleTable_bag.clearSelection();
      }
    },
    back() {
      this.$router.back();
    }
  }
};
</script>
<style lang="scss">
#addonline {
  .custom-1 {
    width: 100%;
  }
  padding-bottom: 100px;
  .el-form {
    width: 70%;
    .title {
      font-size: 16px;
      color: #6d2377;
      padding: 20px 30px 30px 20px;
    }
  }
  .el-dialog {
    //width: 1400px;
    .input {
      width: 200px;
    }
  }
  .el-form-item__content .btn {
    background: #c8c9cc !important;
    border-color: #c8c9cc !important;
    color: #fff;
    margin-left: 142px;
  }
  .times {
    .el-radio {
      float: left;
      height: 34px;
      line-height: 34px;
      margin-right: 10px;
    }
    .el-form-item__content {
      float: left;
      .el-date-editor {
        width: 271px !important;
      }
    }
  }
  .el-input-number {
    width: 315px;
    .el-input__inner {
      // width: 315px;
      height: 34px;
    }
  }
  .quota {
    .el-form-item__error {
      margin-left: 64px;
    }
  }
  .el-radio-group {
    width: 400px;
  }
  .img-info {
    float: left;
    font-size: 12px;
    line-height: 1.5;
    margin-top: 20px;
    margin-left: 20px;
  }
}
</style>
